package com.easylinkin.linkappapi.openapi.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.easylinkin.linkappapi.machinery.controller.MachineryRecordController;
import com.easylinkin.linkappapi.machinery.controller.MachineryUserTypeController;
import com.easylinkin.linkappapi.machinery.entity.MachineryRecord;
import com.easylinkin.linkappapi.machinery.entity.MachineryType;
import com.easylinkin.linkappapi.safe.controller.HiddenDangerController;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.sevice.LinkappTenantService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.alarm.entity.Alarm;
import com.easylinkin.linkappapi.alarm.entity.AlarmStatistic;
import com.easylinkin.linkappapi.alarm.service.AlarmService;
import com.easylinkin.linkappapi.application.service.ApplicationService;
import com.easylinkin.linkappapi.asset.entity.Asset;
import com.easylinkin.linkappapi.asset.mapper.AssetMapper;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.mapper.DeviceMapper;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.deviceattribute.entity.DeviceAttribute;
import com.easylinkin.linkappapi.deviceattribute.service.DeviceAttributeService;
import com.easylinkin.linkappapi.deviceattributestatus.entity.DeviceAttributeStatus;
import com.easylinkin.linkappapi.deviceattributestatus.service.DeviceAttributeStatusService;
import com.easylinkin.linkappapi.deviceunit.entity.DeviceUnit;
import com.easylinkin.linkappapi.intelligentrule.entity.IntelligentRuleExpression;
import com.easylinkin.linkappapi.openapi.dto.BuriedPointDTO;
import com.easylinkin.linkappapi.openapi.dto.RealTimeWeather;
import com.easylinkin.linkappapi.openapi.service.OpenApiDataVService;
import com.easylinkin.linkappapi.openapi.service.OpenApiService;
import com.easylinkin.linkappapi.openapi.service.WeatherTimingSynService;
import com.easylinkin.linkappapi.openapi.util.HttpClientUtil;
import com.easylinkin.linkappapi.openapi.util.IpUtil;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.service.LinkappUserService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

@Api(value = "openApi-DataV控制器", tags = {"dataV调用API接口"})
@RestController
@Slf4j
@RequestMapping({"/openAPI", "openapi"})
public class OpenApiDataVController {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Resource
  private OpenApiDataVService openApiDataVService;

  @Resource
  private DeviceMapper deviceMapper;
  @Resource
  private AssetMapper assetMapper;
  @Resource
  private AlarmService alarmService;

  @Resource
  private DeviceService deviceService;
  @Resource
  private LinkappUserService userService;

  @Resource
  private DeviceAttributeStatusService deviceAttributeStatusService;
  @Resource
  private DeviceAttributeService deviceAttributeService;

  @Resource
  private OpenApiService openApiService;
  @Resource
  private WeatherTimingSynService weatherTimingSynService;
  private static JSONArray cityCode;
  @Autowired
  ApplicationService applicationService;
  @Autowired
  HiddenDangerController hiddenDangerController;
  @Autowired
  LinkappTenantService linkappTenantService;

  @Autowired
  MachineryRecordController machineryRecordController;
  @Autowired
  MachineryUserTypeController machineryUserTypeController;

  /**
   * 查询可添加的设备类型
   */
  @PostMapping("/machineryUserType/typeList")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryTypeList(@RequestBody MachineryType machineryType) {
    return machineryUserTypeController.queryTypeList(machineryType);
  }

  /**
   * @Description: 查询管理人员
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("machineryRecord/machineryUser/{code}")
  @ApiOperation("查询设备特性参数")
  public RestMessage getUser(@PathVariable("code") String code, @RequestParam("tenantId") String tenantId) {
    Assert.notNull(tenantId, "参数tenantId 不能为空");
    return machineryRecordController.getUser(code, tenantId);
  }


  /**
   * @Description: 根据id查询电子档案详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("/machineryRecord/{id}")
  @ApiOperation("根据id查询电子档案详情")
  public RestMessage findById(@PathVariable("id")Integer id) {
    return machineryRecordController.findById(id);
  }

  /**
   * 根据条件，分页(不分页)查询
   */
  @PostMapping("/machineryRecord/list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryListByPage(@RequestBody RequestModel<MachineryRecord> requestModel) {
    return machineryRecordController.queryListByPage(requestModel,true);
  }


  private String getTenantIdByProjectId(Long projectId) {
    if (projectId == null) {
      return null;
    }
    LinkappTenant tenant = linkappTenantService.getOneByProjectId(projectId);
    if (!ObjectUtils.isEmpty(tenant)) {
      return tenant.getId();
    }
    return "null";
  }

  /**
   * 分包单位统计
   */
  @GetMapping("/hiddenDanger/getUnitIdCount")
  @ApiOperation("分包单位统计")
  public RestMessage getUnitIdCount(@RequestParam(value = "startTime"
          , required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime
          ,@RequestParam(value = "projectId", required = false) Long projectId) {
    String tenantId = getTenantIdByProjectId(projectId);
    return hiddenDangerController.getUnitIdCount(startTime, endTime,tenantId);
  }



  /**
   * 获取检查台账首页统计
   *
   * @return
   */
  @GetMapping("hiddenDanger/getTypeCount")
  @ApiOperation("检查台账按类别维度统计")
  public RestMessage getTypeCount(@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime, @RequestParam(value = "projectId", required = false) Long projectId) {
    String tenantId = getTenantIdByProjectId(projectId);
    return hiddenDangerController.getTypeCount(startTime, endTime,tenantId);
  }


  /**
   * 获取检查台账首页统计
   *
   * @return
   */
  @GetMapping("/hiddenDanger/getCount")
  @ApiOperation("检查台账首页统计")
  public RestMessage getCount(@RequestParam(value = "content", required = false) String content,
                              @RequestParam(value = "linkUnitId", required = false) String linkUnitId, @RequestParam(value = "rectifyUid", required = false) Long rectifyUid,
                              @RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false ) String endTime ,@RequestParam(value = "projectId", required = false) Long projectId) {

    String tenantId = getTenantIdByProjectId(projectId);
    return hiddenDangerController.getCount(content, linkUnitId, rectifyUid, startTime, endTime,tenantId);
  }

  /**
   * 获取检查台账首页统计
   *
   * @return
   */
  @GetMapping("/hiddenDanger/getPartCount")
  @ApiOperation("检查台账按检查部位维度统计")
  public RestMessage getPartCount(@RequestParam(value = "startTime",required = false) String startTime,@RequestParam(value = "endTime",required = false) String endTime,@RequestParam(value = "projectId", required = false) Long projectId) {
    String tenantId = getTenantIdByProjectId(projectId);
    return hiddenDangerController.getPartCount(startTime,endTime,tenantId);
  }
  @PostMapping("alarmInfo/getPageGlobal")
  @ApiOperation("查询告警分页列表-所有项目")
  public RestMessage getAlarmPageGlobal(@RequestBody RequestModel<Alarm> requestModel) {
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<Alarm> record = alarmService.getAlarmPageGlobal(requestModel.getPage(), requestModel.getCustomQueryParams());
    return RestBuilders.successBuilder().data(record).build();
  }


  @ApiOperation("设备属性历史数据流水查询")
  @ApiImplicitParam(name = "getHistoricDataPageFromEs", value = "设备属性历史数据流水查询", required = true, dataType = "DeviceAttributeStatus")
  @PostMapping("/datav/getHistoricDataPageFromEs")
  public RestMessage getHistoricDataPageFromEs(
      @RequestBody RequestModel<DeviceAttributeStatus> requestModel) {
    Assert.notNull(requestModel, "参数为空");
    Assert.notNull(requestModel.getPage(), "分页参数为空");
    DeviceAttributeStatus deviceAttributeStatus = requestModel.getCustomQueryParams();
    Assert.notNull(deviceAttributeStatus, "getCustomQueryParams 参数不完整");
    if (ObjectUtils.isEmpty(deviceAttributeStatus.getQueryTimeEnd())) {
      deviceAttributeStatus.setQueryTimeEnd(DateUtil.getYYYYMMDDHHMMSSDate(new Date()));
    }
    if (ObjectUtils.isEmpty(deviceAttributeStatus.getQueryTimeStart())) {
      deviceAttributeStatus.setQueryTimeStart(DateUtil.getYYYYMMDDHHMMSSDate(
          new Date(System.currentTimeMillis() - 365 * 24 * 60 * 60 * 1000L)));
    }

    Assert.notNull(requestModel.getCustomQueryParams(), "参数不完整");
    return RestBuilders.successBuilder()
        .data(deviceAttributeStatusService.getHistoricDataFromEs(requestModel)).build();
  }


  //设备总数数量统计、在线、离线
  @ApiOperation("设备总数数量统计、在线、离线")
  @PostMapping("/datav/device/deviceCount")
  public Map deviceCount() {
    Map map = new HashMap();
    //总数
    Device device = new Device();
    device.setQueryTimeEnd(DateUtil.overQueryTimeEnd(device.getQueryTimeEnd()));
    List<Device> list = deviceMapper.selectDevices(device);
    Integer deviceCount = list.size();
    map.put("deviceCount", deviceCount);
    //在线
    device.setOnlineState(1);
    list = deviceMapper.selectDevices(device);
    Integer onlineCount = list.size();
    map.put("onlineCount", onlineCount);
    //离线
    device.setOnlineState(0);
    list = deviceMapper.selectDevices(device);
    Integer offlineCount = list.size();
    map.put("offlineCount", offlineCount);
    //在线率
    Double onlineRate = Double.valueOf(onlineCount) / Double.valueOf(deviceCount);
    map.put("onlineRate", onlineRate);
    return map;
  }

  @ApiOperation("设备资产数据统计")
  @PostMapping("/datav/asset/assetAudit")
  public Map assetAudit() {
    Map map = new HashMap();
    Asset asset = new Asset();
    List<Asset> list = assetMapper.getAssets(asset);
    Integer assetCount = list.size();
    map.put("assetCount", assetCount);

    Map<String, Integer> counts = assetMapper.queryDayAndMonthCreates();
    map.put("monthnumber", counts.get("monthnumber"));

    map.put("daynumber", counts.get("daynumber"));

    return map;
  }

  /**
   * 查询设备当天的分时数据 和这个接口getHistoricDataCurrDayNew是一样的 2021-11-10
   *
   * @param deviceAttributeStatus
   * @return
   */
  @ApiOperation("查询设备当天的分时数据")
  @PostMapping("/datav/getHistoricDataCurrDay")
  public RestMessage getHistoricDataCurrDay(
      @RequestBody DeviceAttributeStatus deviceAttributeStatus) {
    Assert.notNull(deviceAttributeStatus, "参数为空");
    return RestBuilders.successBuilder()
        .data(openApiDataVService.getHistoricDataCurrDay(deviceAttributeStatus)).build();
  }

  /**
   * 查询设备当天的分时数据
   *
   * @param deviceAttributeStatus
   * @return
   */
  @ApiOperation("查询设备当天的分时数据")
  @PostMapping("/datav/getHistoricDataCurrDayNew")
  public RestMessage getHistoricDataCurrDayNew(
      @RequestBody DeviceAttributeStatus deviceAttributeStatus) {
    Assert.notNull(deviceAttributeStatus, "参数为空");
//        return RestBuilders.successBuilder().data(openApiDataVService.getHistoricDataCurrDayNew(deviceAttributeStatus)).build();
    return RestBuilders.successBuilder()
        .data(openApiDataVService.getHistoricDataCurrDay(deviceAttributeStatus)).build();
  }

  @ApiOperation("告警信息已处理、未处理数据统计")
  @PostMapping("/datav/alarmInfo/alarmInfoAudit")
  public Map alarmInfoAudit() {
    Map map = new HashMap();
    Page page = new Page();
    Alarm alarm = new Alarm();
    Device device = new Device();
    alarm.setDevice(device);
    IPage<Alarm> record = alarmService.getAlarmPage(page, alarm);
    Long alarmCount = record.getTotal();
    map.put("alarmCount", alarmCount);

    alarm.setStatus(1);
    record = alarmService.getAlarmPage(page, alarm);
    map.put("untreatedCount", record.getTotal());

    alarm.setStatus(2);
    record = alarmService.getAlarmPage(page, alarm);
    map.put("treatedCount", record.getTotal());

    return map;
  }

  /**
   * 近七天告警已/未处理统计整合
   *
   * @return
   */
  @ApiOperation("近七天告警已/未处理统计整合")
  @PostMapping("/datav/alarmInfo/getAlarmStatisticsByStatus")
  public Map getAlarmStatisticsByStatus() {
    Map map = new HashMap();
    Alarm alarm = new Alarm();
    alarm.setStatisticsTimeType("%Y-%m-%d");
    alarm.setStatus(1);
    List<AlarmStatistic> unHandlerAlarmStatistics = alarmService.getAlarmStatisticsByStatus(alarm);
    map.put("unHandlerAlarm", unHandlerAlarmStatistics);

    alarm.setStatus(2);
    List<AlarmStatistic> handlerAlarmStatistics = alarmService.getAlarmStatisticsByStatus(alarm);
    map.put("handlerAlarm", handlerAlarmStatistics);
    return map;
  }

  /**
   * 荆州油烟要求只统计 当日产生的维度统计 近七天告警已/未处理统计整合
   *
   * @return
   */
  @ApiOperation("近七天告警已/未处理统计整合")
  @PostMapping("/datav/alarmInfo/getAlarmStatisticsByStatus2")
  public Map getAlarmStatisticsByStatus2() {
    Map map = new HashMap();
    Alarm alarm = new Alarm();
    alarm.setStatisticsTimeType("%Y-%m-%d");
    alarm.setStatus(1);
    List<AlarmStatistic> unHandlerAlarmStatistics = alarmService.getAlarmStatisticsByStatus2(alarm);
    map.put("unHandlerAlarm", unHandlerAlarmStatistics);

    alarm.setStatus(2);
    List<AlarmStatistic> handlerAlarmStatistics = alarmService.getAlarmStatisticsByStatus2(alarm);
    map.put("handlerAlarm", handlerAlarmStatistics);
    return map;
  }


  /**
   * 近七天设备在/离线统计整合
   *
   * @return
   */
  @ApiOperation("近七天设备在/离线统计整合")
  @PostMapping("/datav/device/getStatisticsDeviceCount")
  public Map getStatisticsDeviceCount() {
    Map map = new HashMap();
    Page page = new Page();
    page.setCurrent(0);
    page.setSize(7);
    Device device = new Device();
    device.setStatisticsTimeType("%Y-%m-%d");
    device.setQueryTimeEnd(
        DateUtil.format(DateUtil.addDay(new Date(), 1), DateUtil.DATE_TIME_FORMAT_DAY));
    device.setOnlineState(1);
    List<Map> onlineStatisticsDeviceCount = deviceService.getStatisticsDeviceCount(page, device);
    map.put("onlineStatisticsMap", onlineStatisticsDeviceCount);

    device.setOnlineState(0);
    List<Map> handlerAlarmStatistics = deviceService.getStatisticsDeviceCount(page, device);
    map.put("offlineStatisticsMap", handlerAlarmStatistics);
    return map;
  }

  /**
   * 按照空间分组统计，今日的告警的设备数（今日产生的）以及正常的设备数
   *
   * @param device
   * @return
   */
  @ApiOperation("根据空间统计设备状态")
  @PostMapping("/datav/device/statisticDeviceStatusCountBySpace")
  public RestMessage statisticDeviceStatusCountBySpace(@RequestBody Device device) {
    return RestBuilders.successBuilder()
        .data(deviceService.statisticDeviceStatusCountBySpace(device)).build();
  }

  /**
   * 根据设备属性做统计，就是在原有的设备监控高级查询上做了一些扩展：支持设备型号来查询，不必要写死设备属性id和设备型号id
   *
   * @return
   */
  @ApiOperation("根据设备属性做统计")
  @PostMapping("/datav/device/getDeviceMaintainCount")
  public RestMessage getDeviceMaintainCount(@RequestBody RequestModel<Device> requestModel) {
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    Device customQueryParams = requestModel.getCustomQueryParams();
    //设备型号编码获取设备型号数据和属性数据
    String deviceUnitCode = customQueryParams.getMoniterCommonQuery();
    Page page = new Page();
    page.setCurrent(0);
    page.setSize(7);
    DeviceUnit deviceUnit = new DeviceUnit();
    deviceUnit.setCode(deviceUnitCode);
    Long userId = linkappUserContextProducer.getCurrent().getId();
    List<DeviceUnit> deviceUnitList = applicationService.selectApplicationDeviceUnitByUser(
        userId.toString());
    if (ObjectUtils.isEmpty(deviceUnitList)) {
      return RestBuilders.failureMessage().setMessage("无设备型号数据");
    }
    String deviceUnitId = null;
    for (DeviceUnit deviceUnit1 :
        deviceUnitList) {
      if (deviceUnit1.getCode().equals(deviceUnitCode)) {
        deviceUnitId = deviceUnit1.getId();
      }
    }
    if (deviceUnitId == null) {
      return RestBuilders.failureMessage().setMessage("无设备型号数据");
    }

    customQueryParams.setDeviceUnitId(deviceUnitId);
    DeviceAttribute deviceAttribute = new DeviceAttribute();
    deviceAttribute.setDeviceUnitId(deviceUnitId);
    List<DeviceAttribute> DeviceAttributeList = deviceAttributeService.getAll(deviceAttribute);

    boolean attributeExistFlag = false;
    for (DeviceAttribute deviceAttribute2 :
        DeviceAttributeList) {
      List<IntelligentRuleExpression> propertyExpressions = customQueryParams.getPropertyExpressions();
      IntelligentRuleExpression intelligentRuleExpression = propertyExpressions.get(0);
      String deviceAttributeName = intelligentRuleExpression.getDeviceAttributeName();
      if (deviceAttribute2.getName().equals(deviceAttributeName)) {
        intelligentRuleExpression.setDeviceAttributeId(deviceAttribute2.getId());
        attributeExistFlag = true;
      }
    }
    if (!attributeExistFlag) {
      return RestBuilders.failureMessage().setMessage("不存在查询需要的属性名称");
    }
    log.info("getDeviceMaintainCount 重新组装的参数打印：" + JSON.toJSONString(
        requestModel.getCustomQueryParams()));

    IPage<Device> record = deviceService.getMonitorPage(requestModel.getPage(),
        requestModel.getCustomQueryParams());
    return RestBuilders.successBuilder().data(record).build();
  }

  @ApiOperation("根据设备类型名称统计各个类型的设备数量")
  @PostMapping("/datav/device/getStatisticsByType")
  public Map getDeviceStatisticsByType() {
    Device device = new Device();
    return deviceService.getStatisticsByType(device);
  }

  @ApiOperation("统计今日、昨日、用户注册总数")
  @PostMapping("/datav/user/userAudit")
  public Map userAudit() {
    String currentDate = DateUtil.getCurrentDateStr(DateUtil.DATE_TIME_FORMAT_DAY);
    String dateExp = "%Y-%m";
    LinkappUser linkappUser = linkappUserContextProducer.getCurrent();
    String tenantId = linkappUser.getTenantId();
    Integer currentMonthCount = userService.auditUser(currentDate, dateExp, tenantId);
    String lastDay = lastDay();
    dateExp = "%Y-%m-%d";
    Integer lastDayCount = userService.auditUser(lastDay, dateExp, tenantId);
    Integer userCount = userService.auditUser(null, null, tenantId);
    Map map = new HashMap();
    map.put("currentMonthCount", currentMonthCount);
    map.put("lastDayCount", lastDayCount);
    map.put("userCount", userCount);
    return map;
  }

  private String lastDay() {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -1); //得到度前一天
    Date date = calendar.getTime();
    DateFormat df = new SimpleDateFormat(DateUtil.DATE_TIME_FORMAT_DAY);
    return df.format(date);
  }

  /**
   * 根据城市名称获取天气信息
   *
   * @param cityKey 示例：北京
   * @return
   */
  @ApiOperation("获取天气信息")
  @PostMapping("getWeather")
  public RestMessage getWeather(String cityKey) {
//    HttpGet httpGet = new HttpGet("http://wthrcdn.etouch.cn/weather_mini?city=" + cityKey);
//    return JSON.parseObject(str);
    //参考文档https://www.sojson.com/api/weather.html
    String cityCode = getCityCode(cityKey);
    Assert.notNull(cityCode,"请输入正确的城市信息");
    HttpGet httpGet = new HttpGet("http://t.weather.itboy.net/api/weather/city/" + cityCode);
    String str = HttpClientUtil.doGet(httpGet);
    return RestBuilders.successBuilder(JSON.parseObject(str)).build();

  }

  /**
   * 根据城市代码和时间条件获取天气信息
   *
   * @param realTimeWeather
   * @return
   */
  @ApiOperation("根据城市代码和时间条件获取天气信息")
  @PostMapping("getWeatherAll")
  public RestMessage getWeather(@RequestBody RealTimeWeather realTimeWeather) {
    List<RealTimeWeather> realTimeWeatherAll = weatherTimingSynService.getRealTimeWeatherAll(
        realTimeWeather);
    return RestBuilders.successBuilder(realTimeWeatherAll).build();
  }

  /**
   * dataV大屏显示当日数据
   *
   * @param requestModel
   * @param type
   * @return
   */
  @ApiOperation("dataV大屏显示当日数据")
  @PostMapping("/datav/getHistoricDataPageFromEsDataV")
  public RestMessage getHistoricDataPageFromEsDataV(
      @RequestBody RequestModel<DeviceAttributeStatus> requestModel,
      @RequestHeader(value = "type", required = false) Integer type) {
    Assert.notNull(requestModel, "参数为空");
    Assert.notNull(requestModel.getPage(), "分页参数为空");
    DeviceAttributeStatus deviceAttributeStatus = requestModel.getCustomQueryParams();
    Assert.notNull(deviceAttributeStatus, "getCustomQueryParams 参数不完整");
    Assert.notNull(requestModel.getCustomQueryParams(), "参数不完整");
    return RestBuilders.successBuilder()
        .data(openApiDataVService.getHistoricDataPageFromEsDataV(requestModel, type)).build();
  }

  /**
   * @Description: 增加埋点 页面添加需求设置参数：`system '系统(oms,emp,wx)' `mainModule'主埋点', `sonModule'子埋点',
   * `content '埋点内容',
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("datav/buriedPoint")
  @ApiOperation("增加埋点")
  public RestMessage insertBuriedPoint(@RequestBody BuriedPointDTO buriedPoint,
      HttpServletRequest request) throws Exception {
    //获取请求信息
    getFromRequest(buriedPoint, request);
    openApiService.insertBuriedPoint(buriedPoint);
    return RestBuilders.successMessage();
  }

  private void getFromRequest(BuriedPointDTO buriedPoint, HttpServletRequest request) {
    UserAgent userAgent = IpUtil.getUserAgent(request);
    Browser browser = userAgent.getBrowser();
    Version browserVersion = userAgent.getBrowserVersion();
    OperatingSystem operatingSystem = userAgent.getOperatingSystem();
    buriedPoint.setEquipment(
        operatingSystem.getDeviceType().getName() + StringUtils.SPACE + operatingSystem.getName());
    buriedPoint.setBrowser(browser.getName() + StringUtils.SPACE + browserVersion.getVersion());
    //设置ip和位置信息
    String ipAddress = IpUtil.getIPAddress(request);
    buriedPoint.setIp(ipAddress);
  }

  /**
   * 根据设备属性过滤条件做统计
   * 暂时只做设备工作状态条件过滤、物模型型号
   *
   * @return
   */
  @ApiOperation("根据设备属性过滤条件做统计")
  @PostMapping("/datav/device/countByCustom")
  public RestMessage countByCustom(@RequestBody RequestModel<Device> requestModel) {
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Device customQueryParams = requestModel.getCustomQueryParams();
    //设备型号编码获取设备型号数据和属性数据
    String deviceUnitCode = customQueryParams.getMoniterCommonQuery();

    DeviceUnit deviceUnit = new DeviceUnit();
    deviceUnit.setCode(deviceUnitCode);
    Long userId = linkappUserContextProducer.getCurrent().getId();
    List<DeviceUnit> deviceUnitList = applicationService.selectApplicationDeviceUnitByUser(
        userId.toString());
    if (ObjectUtils.isEmpty(deviceUnitList)) {
      return RestBuilders.failureMessage().setMessage("无设备型号数据");
    }
    String deviceUnitId = null;
    for (DeviceUnit deviceUnit1 :
        deviceUnitList) {
      if (deviceUnit1.getCode().equals(deviceUnitCode)) {
        deviceUnitId = deviceUnit1.getId();
      }
    }
    if (StringUtils.isNotBlank(deviceUnitCode) && deviceUnitId == null) {
      return RestBuilders.failureMessage().setMessage("无设备型号数据");
    }

    customQueryParams.setDeviceUnitId(deviceUnitId);

    log.info("countByCustom 重新组装的参数打印：" + JSON.toJSONString(
        requestModel.getCustomQueryParams()));

    QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    deviceQueryWrapper.eq("tenant_id", tenantId);
    deviceQueryWrapper.eq("delete_state", customQueryParams.getDeleteState());
    if (StringUtils.isNotBlank(customQueryParams.getDeviceUnitId())){
      deviceQueryWrapper.eq("device_unit_id",customQueryParams.getDeviceUnitId());
    }
    if (customQueryParams.getWorkStatus() != null){
      deviceQueryWrapper.eq("work_status",customQueryParams.getWorkStatus());
    }
    int count = deviceService.count(deviceQueryWrapper);
    return RestBuilders.successBuilder().data(count).build();
  }

  static String getCityCode(String name){
    if(cityCode==null){
      try {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/cityCode.json");
        cityCode = JSONObject.parseArray(IOUtils.toString(is, "utf-8"));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    String cityCodeStr = null;
    for (int i=0;i<cityCode.size();i++){
      JSONObject jsonObject = (JSONObject) cityCode.get(i);
      String city_name = jsonObject.getString("city_name");
      if(city_name!=null && city_name.equals(name)){
        cityCodeStr = jsonObject.getString("city_code");
        break;
      }
    }
    return cityCodeStr;
  }

}
